package com.zoke.support.image.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.widget.GridView;

import com.zoke.support.R;
import com.zoke.support.base.BaseActivity;
import com.zoke.support.config.ZokeConfig;
import com.zoke.support.image.ImageBean;
import com.zoke.support.image.ImageGroupsGridAdapter;
import com.zoke.support.task.SimpleAsync;
import com.zoke.support.task.SimpleAsync.Callback;
import com.zoke.support.view.ZokeToast;

/**
 * 手机相册 界面内的ListView必须是XlistView id必须是：;
 * 
 * @author JackWu
 * @version
 * @date 2014-2-17
 * @_QQ_ 651319154
 */
public class GalleryActivity extends BaseActivity {
	/** 相册引用 **/
	private HashMap<String, List<String>> mGruopMap = new HashMap<String, List<String>>();
	protected List<ImageBean> mList = new ArrayList<ImageBean>();
	protected ImageGroupsGridAdapter mAdapter;

	private int mType;

	/** 操作类型 **/
	public static final String HANDLETYPE = "_phototype";
	/** 更多相册时 需要传个最大值 **/
	public static final String MAXMORE = "_photomoremax";
	private int mMaxMore;
	private GridView mGridView;

	/** 操作图片的类型 **/
	public class HandleType {
		private HandleType() {
		}

		/** 支持1张并返回裁剪图片 **/
		public static final int CROP = 10;
		/** 支持1张 直接处理压缩返回 **/
		public static final int ONE = 11;
		/** 支持用户多张返回 **/
		public static final int MORE = 12;
		/** 支持用户对图片处理效果 **/
		public static final int FILTER = 13;
	}

	/** 相册返回码 要与操作图片的类型一致 **/
	public class PhotoRequestCode {
		/** 支持1张并返回裁剪图片 **/
		public static final int CROP = 10;
		/** 支持1张 直接处理压缩返回 **/
		public static final int ONE = 11;
		/** 支持用户多张返回 **/
		public static final int MORE = 12;
		/** 支持用户对图片处理效果 **/
		public static final int FILTER = 13;
		/** 返回结果获取码 **/
		public static final String REQUESTKEY = "_photos_result_";
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_images1);
		mType = getIntent().getIntExtra(HANDLETYPE, 1);// 默认是支持单张图片的获取
		mMaxMore = getIntent().getIntExtra(MAXMORE, 9);//默认不传是9张
		mTitleManager.setTitle("手机相册").setLeftIcon(R.drawable.app_title_back);
		mEnableSwipeRight = true;
		mGridView = (GridView) findViewById(R.id._gridview);
		mAdapter = new ImageGroupsGridAdapter(GalleryActivity.this, mList,
				mGruopMap, mType,mMaxMore);
		mGridView.setAdapter(mAdapter);
		try {
			preparePhotos();
		} catch (Exception e) {
			ZokeToast.show(getApplicationContext(), "加载失败");
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null) {
			return;
		}
		setResult(resultCode, data);
		GalleryActivity.this.onBackPressed();
	}

	@Override
	protected void handleMsg(Message msg) {
		super.handleMsg(msg);
		int id = msg.what;
		if (id == ZokeConfig.SCAN_OK) {
			// 加载结束
			List<ImageBean> list = subGroupOfImage(mGruopMap);
			if (list != null && list.size() != 0) {
				mList.clear();
				mList.addAll(list);
				mAdapter.notifyDataSetChanged();
			}
			return;
		}
	}

	/** 从sd卡获取图片 **/
	protected void preparePhotos() {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			ZokeToast.show(getApplicationContext(),
					getResources().getString(R.string._sdcard_failed));
			return;
		}
		// 加载
		new SimpleAsync(new Callback() {
			@Override
			public void onStart() {
				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = GalleryActivity.this
						.getContentResolver();
				int size = 1024 * 1024 * 10;
				Cursor mCursor = mContentResolver.query(mImageUri, null,
						MediaColumns.MIME_TYPE + "=? or "
								+ MediaColumns.MIME_TYPE + "=? and "
								+ MediaColumns.SIZE + ">?", new String[] {
								"image/jpeg", "image/png", size + "" },
						MediaColumns.TITLE);

				while (mCursor.moveToNext()) {
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaColumns.DATA));
					String parentName = new File(path).getParentFile()
							.getName();
					if (!mGruopMap.containsKey(parentName)) {
						List<String> chileList = new ArrayList<String>();
						chileList.add(path);
						mGruopMap.put(parentName, chileList);
					} else {
						mGruopMap.get(parentName).add(path);
					}
				}
				mCursor.close();
				mHandler.sendEmptyMessage(ZokeConfig.SCAN_OK);
			}

			@Override
			public void onPrepare() {
			}

			@Override
			public void onFinish() {
			}
		}).go();
	}

	/**
	 * 组装分组界面GridView的数据源，因为我们扫描手机的时候将图片信息放在HashMap中 所以需要遍历HashMap将数据组装成List
	 * 
	 * @param mGruopMap
	 * @return
	 */
	private List<ImageBean> subGroupOfImage(
			HashMap<String, List<String>> mGruopMap) {
		if (mGruopMap.size() == 0) {
			return null;
		}
		List<ImageBean> list = new ArrayList<ImageBean>();
		Iterator<Map.Entry<String, List<String>>> it = mGruopMap.entrySet()
				.iterator();
		while (it.hasNext()) {
			Map.Entry<String, List<String>> entry = it.next();
			ImageBean mImageBean = new ImageBean();
			String key = entry.getKey();
			List<String> value = entry.getValue();
			mImageBean.setFolderName(key);
			mImageBean.setImageCounts(value.size());
			mImageBean.setTopImagePath(value.get(0));// 获取该组的第一张图片
			if ("Camera".endsWith(key) || "100MEDIA".equals(key)) {
				list.add(0, mImageBean);
			} else {
				list.add(mImageBean);
			}
		}

		return list;
	}

}
